package com.luke.dt.user.service;

import com.alibaba.fastjson.JSONObject;
import com.luke.dt.commons.entitys.shared.TblDtJudeDuplicate;
import com.luke.dt.commons.enums.ErrorCodeEnums;
import com.luke.dt.commons.exception.ServiceException;
import com.luke.dt.user.dao.TblDtJudeDuplicateMapper;
import com.luke.dt.user.dao.TblUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;

@Slf4j
@Service
@Transactional(readOnly = true)
public class JudeDuplicateServiceImpl implements JudeDuplicateService{

    @Autowired(required = false)
    private TblUserMapper tblUserMapper;

    @Autowired(required = false)
    private TblDtJudeDuplicateMapper tblDtJudeDuplicateMapper;

    @Transactional(readOnly = false)
    @Override
    public TblDtJudeDuplicate handleReduUserBalance(String msg) throws ServiceException {
        log.info("handleDtQueueMsg:{}",msg);
        //这里这是统一处理了msg，实际环境可能需要在msg包含业务值，表示msg是什么业务的数据
        JSONObject jsonObject = JSONObject.parseObject(msg);
        Long msgId = Long.valueOf(jsonObject.get("msgId").toString());
        JSONObject msgData = jsonObject.getJSONObject("msgData");

        //查询是否已经处理过了这条消息（防止重复消费）
        TblDtJudeDuplicate findJudeDuplicate = new TblDtJudeDuplicate();
        findJudeDuplicate.setMsgId(msgId);
        TblDtJudeDuplicate dbJudeDuplicate = tblDtJudeDuplicateMapper.selectOne(findJudeDuplicate);
        if(dbJudeDuplicate == null){//第一次处理
            TblDtJudeDuplicate saveTblDtJudeDuplicate = new TblDtJudeDuplicate();
            saveTblDtJudeDuplicate.setCreateTime(new Date());
            saveTblDtJudeDuplicate.setMsgId(msgId);
            saveTblDtJudeDuplicate.setMsgData(msgData.toJSONString());
            saveTblDtJudeDuplicate.setHandleNum(0);//处理次数
            saveTblDtJudeDuplicate.setStatusVal(1);//预处理
            tblDtJudeDuplicateMapper.insertUseGeneratedKeys(saveTblDtJudeDuplicate);
            dbJudeDuplicate = saveTblDtJudeDuplicate;
        }

        //处理消息业务逻辑
        int statusVal = dbJudeDuplicate.getStatusVal();//消息状态
        if(statusVal == 1){//待处理
            Long userId = Long.valueOf(msgData.get("id").toString());
            Float balance = Float.valueOf(msgData.get("balance").toString());
            tblUserMapper.updateUserBalance(userId,balance);
            //更新防重表
            TblDtJudeDuplicate updateJudeDuplicate = new TblDtJudeDuplicate();
            updateJudeDuplicate.setId(dbJudeDuplicate.getId());
            updateJudeDuplicate.setStatusVal(2);//处理成功
            updateJudeDuplicate.setUpdateTime(new Date());
            tblDtJudeDuplicateMapper.updateByPrimaryKeySelective(updateJudeDuplicate);
            return updateJudeDuplicate;
        }else if(statusVal == 3){//处理失败
            if(dbJudeDuplicate.getHandleNum() <= 3){//超过三次，人工介入
                Long userId = Long.valueOf(msgData.get("id").toString());
                Float balance = Float.valueOf(msgData.get("balance").toString());
                tblUserMapper.updateUserBalance(userId,balance);
                //更新防重表
                TblDtJudeDuplicate updateJudeDuplicate = new TblDtJudeDuplicate();
                updateJudeDuplicate.setId(dbJudeDuplicate.getId());
                updateJudeDuplicate.setStatusVal(2);//处理成功
                updateJudeDuplicate.setUpdateTime(new Date());
                updateJudeDuplicate.setHandleNum(dbJudeDuplicate.getHandleNum()+1);
                tblDtJudeDuplicateMapper.updateByPrimaryKeySelective(updateJudeDuplicate);
                return updateJudeDuplicate;
            }
        }
        return dbJudeDuplicate;
    }

    @Transactional(readOnly = false)
    @Override
    public Integer handleMsgFail(String msg) throws ServiceException {
        log.info("handleMsgFail:{}",msg);
        //这里这是统一处理了msg，实际环境可能需要在msg包含业务值，表示msg是什么业务的数据
        JSONObject jsonObject = JSONObject.parseObject(msg);
        Long msgId = Long.valueOf(jsonObject.get("msgId").toString());
        //JSONObject msgData = jsonObject.getJSONObject("msgData");

        TblDtJudeDuplicate findJudeDuplicate = new TblDtJudeDuplicate();
        findJudeDuplicate.setMsgId(msgId);
        TblDtJudeDuplicate dbJudeDuplicate = tblDtJudeDuplicateMapper.selectOne(findJudeDuplicate);
        if (dbJudeDuplicate == null){
            throw new ServiceException(ErrorCodeEnums.ERROR_CODE_JUDE_FIND_FAIL.getCode(),
                    ErrorCodeEnums.ERROR_CODE_JUDE_FIND_FAIL.getMessage());
        }

        if(dbJudeDuplicate.getHandleNum() < 3){
            //更新防重表
            TblDtJudeDuplicate updateJudeDuplicate = new TblDtJudeDuplicate();
            updateJudeDuplicate.setId(dbJudeDuplicate.getId());
            updateJudeDuplicate.setStatusVal(3);//处理失败
            updateJudeDuplicate.setUpdateTime(new Date());
            updateJudeDuplicate.setHandleNum(dbJudeDuplicate.getHandleNum()+1);
            tblDtJudeDuplicateMapper.updateByPrimaryKeySelective(updateJudeDuplicate);
            return dbJudeDuplicate.getHandleNum()+1;
        }else{
            log.error("已经处理超过三次");
            return dbJudeDuplicate.getHandleNum();
        }
    }
}
